#define CONV(v) (struct sockaddr *)(v)

#include "UdpClient.hpp"

#include <iostream>
#include <string>
#include <cstring>

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdint.h>
#include <arpa/inet.h>


int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "severip serverport" <<std::endl;
        exit(1);
    }

    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error!" <<std::endl;
        exit(2);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());
    server.sin_port = ::htons(serverport);

    while (true)
    {
        std::cout << "please Enter# ";
        std::string msg;
        std::getline(std::cin, msg);

        ::sendto(sockfd, msg.c_str(), msg.size(), 0, CONV(&server), sizeof(server));

        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);

        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}